<template>
  <div>
    <template v-if="editing">
      <tag-select
        :selected-tags.sync="tags"
        :is-label="false"
        :quick-add="false"
        size="small"
        class="m-b-8"
      />
    </template>
    <template v-else>
      <el-tag v-for="tag in curDoc.tags" :key="tag" size="small" disable-transitions>
        {{ tag }}
      </el-tag>
    </template>
    <template v-if="curUser.id">
      <el-button
        size="small"
        type="primary"
        v-if="editing"
        @click="saveTags"
        :loading="loading"
        class="m-r-10">
        保存编辑
      </el-button>
      <span
        @click="handleEdit"
        :class="['el-link', editing ? 'el-link--info' : 'el-link--primary']">
        {{ editing ? '取消编辑' : '编辑标签' }}
      </span>
    </template>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import TagSelect from '@/components/shared/TagSelect';

export default {
  name: 'edit-tags',
  components: {
    TagSelect,
  },
  data() {
    return {
      editing: false,
      tags: [],
      loading: false,
    };
  },
  computed: {
    ...mapState({
      curUser: 'currentUser',
      curDoc: 'currentDocument',
      curSpace: 'currentSpace',
    }),
    ...mapGetters(['isWebAdmin', 'isSpaceOwner', 'isSpaceAdmin']),
  },
  methods: {
    ...mapActions({ setCurDoc: 'setCurrentDocument' }),
    handleEdit() {
      if (!this.editing) this.tags = JSON.parse(JSON.stringify(this.curDoc)).tags; // 进入编辑时初始化
      this.editing = !this.editing;
    },
    saveTags() {
      this.loading = true;
      this.$api.spaceContributions.create({
        action: 'update',
        spaceId: this.$route.params.spaceId,
        oldDocId: this.curDoc.id,
        title: `修改了《${this.curDoc.title}》的标签`,
        resources: [{
          class_type: 'ProductLocalFile',
          title: this.curDoc.title,
          tag_titles: this.tags,
        }],
      }).then((res) => {
        this.$message.success('提交成功');
        if (this.curSpace.autoAccept || this.isSpaceOwner || this.isSpaceAdmin || this.isWebAdmin) {
          const doc = Object.assign({}, this.curDoc, { tags: this.tags });
          this.setCurDoc(doc);
          this.editing = false;
        } else this.$router.push(`/spaces/${this.curSpace.id}/contributions/${res.data.id}`);
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
};
</script>

<style></style>
